package com.xh.demo.commons.utils;

import com.xh.demo.commons.asserts.Assert;
import com.xh.demo.commons.enums.MessageEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.CharEncoding;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author wen
 * @apiNote ResponseUtil
 * @since 2021/12/11
 */
@Slf4j
public class ResponseUtil {

    public static void write(Object result) {
        write(result, getResponse());
    }

    public static void write(Object result, HttpServletResponse response) {
        write(result, response, HttpStatus.OK.value());
    }

    public static void write(Object result, HttpServletResponse response, int httpStatus) {
        response.setStatus(httpStatus);
        response.setCharacterEncoding(CharEncoding.UTF_8);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        try (PrintWriter writer = response.getWriter()) {
            writer.write(JacksonUtil.serialize(result));
            writer.flush();
        } catch (IOException ex) {
            log.error("【Response响应服务】Web Response IOException:{}", ex.getMessage());
        }
    }

    public static HttpServletResponse getResponse() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        Assert.isFalse(!(requestAttributes instanceof ServletRequestAttributes), MessageEnum.INVALID_RESPONSE);
        HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse();
        Assert.notNull(response, MessageEnum.INVALID_RESPONSE);
        return response;
    }

}
